import React, { Component, Fragment } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { actionCreators } from '../store';

import { Button, Modal, Form, Input, Select, message } from 'antd';

const { Option } = Select;

class EditConnection extends Component{
  state={
    visible: false,
    dataType: "",
    testCon: {},
  };

  handleClick = (id,dataType) => {
    this.props.getCon(dataType,{id:id});
    this.setState({visible:true});
  };

  handleOk = (values,basicInfo,databaseConfig) => {
    const {testCon} = this.state;
    let dType = databaseConfig.databaseType;
    if(dType){
      let dataType = dType.toLowerCase();
      let databaseId = basicInfo.databaseId;
      let id = basicInfo.id;
      let configName = values.configName;
      let description = values.description?values.description:"";
      let username ="admin";//待修改
      if(dataType==="mysql"||dataType==="sqlserver"||dataType==="mongodb"){
          let host = values.host;
          let port = values.port;
          let userName = values.userName;
          let password = values.password;
          let databaseName = values.databaseName;
          if(JSON.stringify(testCon)!=='{}'){
            if(testCon.host===host&&testCon.port===port&&testCon.userName===userName&&testCon.password===password){//已修改表单信息，进行测试连接的验证
              let params = {configName,description,host,port,userName,password,databaseName,databaseId,id,username};
              this.props.editCon(dataType,params,this.props.searchValue);
              this.formRef1.current.resetFields();
              this.setState({visible:false,testCon:{}});
              this.props.clearConfig();
            }
            else{
              message.error("请先测试连接！");
            }
          }
          else{
            if(databaseConfig.hostName===host&&port===databaseConfig.port&&userName===databaseConfig.userName&&password===databaseConfig.password){//未修改表单信息，进行测试连接的验证
              let params = {configName,description,host,port,userName,password,databaseName,databaseId,id,username};
              this.props.editCon(dataType,params,this.props.searchValue);
              this.formRef1.current.resetFields();
              this.setState({visible:false})
            }
            else{
              message.error("请先测试连接！");
            }
          }
      }else if(dataType==="oracle"){
          let host = values.host;
          let port = values.port;
          let userName = values.userName;
          let password = values.password;
          let database = values.database;
          if(JSON.stringify(testCon)!=='{}'){
            if(testCon.host===host&&testCon.port===port&&testCon.userName===userName&&testCon.password===password&&testCon.database===database){
              let params = {configName,description,host,port,userName,password,database,databaseId,id,username};
              this.props.editCon(dataType,params,this.props.searchValue);
              this.formRef1.current.resetFields();
              this.setState({visible:false,testCon:{}});
            }
            else{
              message.error("请先测试连接！");
            }
          }
          else{
            if(databaseConfig.hostName===host&&port===databaseConfig.port&&userName===databaseConfig.userName&&password===databaseConfig.password&&database===databaseConfig.databaseName){
              let params = {configName,description,host,port,userName,password,database,databaseId,id,username};
              this.props.editCon(dataType,params,this.props.searchValue);
              this.formRef1.current.resetFields();
              this.setState({visible:false,testCon:{}});
            }
            else{
              message.error("请先测试连接！");
            }
          }
      }else if(dataType==="hbase"){
          let master = values.master;
          let zookeeperQueue = values.zookeeperQueue;
          let zookeeperPort = values.zookeeperPort;
          if(JSON.stringify(testCon)!=='{}'){
            if(testCon.master===master&&testCon.zookeeperQueue===zookeeperQueue&&testCon.zookeeperPort===zookeeperPort){
              let params = {configName,description,master,zookeeperQueue,zookeeperPort,username};
              this.props.editCon(dataType,params,this.props.searchValue);
              this.formRef1.current.resetFields();
              this.setState({visible:false,testCon:{}});
            }
            else{
              message.error("请先测试连接！");
            }
          }
          else{
            if(master===databaseConfig.hbaseMaster&&zookeeperQueue===databaseConfig.zookeeperQueue&&zookeeperPort===databaseConfig.zookeeperPort){
              let params = {configName,description,master,zookeeperQueue,zookeeperPort,username};
              this.props.editCon(dataType,params,this.props.searchValue);
              this.formRef1.current.resetFields();
              this.setState({visible:false,testCon:{}});
            }
            else{
              message.error("请先测试连接！");
            }
          }
      }
    }
  };

  handleCancel = () => {
    this.setState({visible:false});
    this.formRef1.current.resetFields();
  };

  chooseType = dataType => {
    this.setState({ dataType });
    this.props.cleanDatabase();
    if(this.state.dataType==="MySQL"||this.state.dataType==="SQLServer"||this.state.dataType==="MongoDB"){//修改数据类型时将表单置空
      this.formRef.current.setFieldsValue({host:undefined,port:undefined,userName:undefined,password:undefined,databaseName:undefined,description:undefined});
    }else if(this.state.dataType==="Oracle"){
      this.formRef.current.setFieldsValue({host:undefined,port:undefined,userName:undefined,password:undefined,database:undefined,description:undefined});
    }else if(this.state.dataType==="HBase"){
      this.formRef.current.setFieldsValue({master:undefined,zookeeperQueue:undefined,zookeeperPort:undefined,description:undefined});
    }
  };

  testCon = (basicInfo,databaseConfig) => {
    let dType = databaseConfig.databaseType;
    if(dType){
      let dataType = dType.toLowerCase();
      if(dataType==="mysql"||dataType==="sqlserver"||dataType==="mongodb"){
        this.formRef1.current.validateFields(["host","port","userName","password"])
        .then(values => {
          let host = values.host;
          let port = values.port;
          let userName = values.userName;
          let password = values.password;
          let params = {host,port,userName,password};
          this.setState({testCon: params});
          this.formRef.current.setFieldsValue({databaseName:undefined});
          this.props.testCon(dataType,params);
          //this.props.getAllDatabase(dataType,params);
        })
      }else if(dataType==="oracle"){
        this.formRef1.current.validateFields(["host","port","userName","password","database"])
        .then(values => {
          let host = values.host;
          let port = values.port;
          let userName = values.userName;
          let password = values.password;
          let database = values.database;
          let params = {host,port,userName,password,database};
          this.setState({testCon: params});
          this.props.testCon(dataType,params);
        })
      }else if(dataType==="hbase"){
        this.formRef1.current.validateFields(["master","zookeeperQueue","zookeeperPort"])
        .then(values => {
          let master = values.master;
          let zookeeperQueue = values.zookeeperQueue;
          let zookeeperPort = values.zookeeperPort;
          let params = {master,zookeeperQueue,zookeeperPort};
          this.setState({testCon: params});
          this.props.testCon(dataType,params);
        })
      }
    }
  };

  dataTypeForm = (basicInfo,databaseConfig) => {
    let dType = databaseConfig.databaseType;
    if(dType){
      let dataType = dType.toLowerCase();
      if(dataType==="mysql"||dataType==="sqlserver"||dataType==="mongodb"){
        return(
        <Fragment>
          <Form.Item
            label="IP" name="host"
            rules={[
              {
                required: true,
                message: '请输入IP地址！',
              },]}>
            <Input placeholder="请输入IP地址"/>
          </Form.Item>
          <Form.Item
            label="端口号" name="port"
            rules={[
              {
                required: true,
                message: '请输入端口号！',
              },]}>
            <Input placeholder="请输入端口号"/>
          </Form.Item>
          <Form.Item
            label="用户名" name="userName"
            rules={[
              {
                required: true,
                message: '请输入用户名！',
              },]}>
            <Input placeholder="请输入用户名"/>
          </Form.Item>
          <Form.Item
            label="密码" name="password"
            rules={[
              {
                required: true,
                message: '请输入密码！',
              },]}>
            <Input.Password placeholder="请输入密码"/>
          </Form.Item>
          {/* <Form.Item
            label="归属部门" name="department"
            initialValue="公安"
            rules={[
              {
                required: true,
              },]}>
            <Input disabled/>
          </Form.Item> */}
          <Button type="primary" onClick={e=>{e.stopPropagation();this.testCon(basicInfo,databaseConfig);}} style={{marginBottom:24}}>测试连接</Button>
          <Form.Item
            label="选择数据库" name="databaseName"
            rules={[
              {
                required: true,
                message: "请选择数据库！"
              },]}>
            <Select placeholder="请选择数据库">
              {
                this.props.database.map(database=>(
                  <Option value={database}>{database}</Option>
                ))
              }
            </Select>
          </Form.Item>
          <Form.Item label="备注" name="description">
            <Input.TextArea rows={4} placeholder="请输入内容"/>
          </Form.Item>
        </Fragment>
        )
      }else if(dataType==="oracle"){
        return(
          <Fragment>
            <Form.Item
              label="IP" name="host"
              rules={[
                {
                  required: true,
                  message: '请输入IP地址！',
                },]}>
              <Input placeholder="请输入IP地址"/>
            </Form.Item>
            <Form.Item
              label="端口号" name="port"
              rules={[
                {
                  required: true,
                  message: '请输入端口号！',
                },]}>
              <Input placeholder="请输入端口号"/>
            </Form.Item>
            <Form.Item
              label="数据库名" name="database"
              rules={[
                {
                  required: true,
                  message: '请输入数据库名！',
                },]}>
              <Input placeholder="请输入数据库名"/>
            </Form.Item>
            <Form.Item
              label="用户名" name="userName"
              rules={[
                {
                  required: true,
                  message: '请输入用户名！',
                },]}>
              <Input placeholder="请输入用户名"/>
            </Form.Item>
            <Form.Item
              label="密码" name="password"
              rules={[
                {
                  required: true,
                  message: '请输入密码！',
                },]}>
              <Input.Password placeholder="请输入密码"/>
            </Form.Item>
            {/* <Form.Item
              label="归属部门" name="department"
              initialValue="公安"
              rules={[
                {
                  required: true,
                },]}>
              <Input disabled/>
            </Form.Item> */}
            <Button type="primary" onClick={e=>{e.stopPropagation();this.testCon(basicInfo,databaseConfig);}} style={{marginBottom:24}}>测试连接</Button>
            <Form.Item label="备注" name="description">
              <Input.TextArea rows={4} placeholder="请输入内容"/>
            </Form.Item>
          </Fragment>
        )
      }else if(dataType==="hbase"){
        return(
          <Fragment>
            <Form.Item
              label="HBase-Master地址" name="master"
              rules={[
                {
                  required: true,
                  message: '请输入HBase-Master地址！',
                },]}>
              <Input placeholder="请输入HBase-Master地址"/>
            </Form.Item>
            <Form.Item
              label="zookeeper队列" name="zookeeperQueue"
              rules={[
                {
                  required: true,
                  message: '请输入zookeeper队列！',
                },]}>
              <Input placeholder="请输入zookeeper队列"/>
            </Form.Item>
            <Form.Item
              label="zookeeper端口号" name="zookeeperPort "
              rules={[
                {
                  required: true,
                  message: '请输入zookeeper端口号！',
                },]}>
              <Input placeholder="请输入zookeeper端口号"/>
            </Form.Item>
            {/* <Form.Item
              label="归属部门" name="department"
              initialValue="公安"
              rules={[
                {
                  required: true,
                },]}>
              <Input disabled/>
            </Form.Item> */}
            <Button type="primary" onClick={e=>{e.stopPropagation();this.testCon(basicInfo,databaseConfig);}} style={{marginBottom:24}}>测试连接</Button>
            <Form.Item label="备注" name="description">
              <Input.TextArea rows={4} placeholder="请输入内容"/>
            </Form.Item>
          </Fragment>
        )
      }
    }
    return null;
  }

  componentDidMount(){
    this.props.onRef(this);
  };

  formRef1 = React.createRef();
  render(){
    let { basicInfo,databaseConfig }= this.props;
    // this.formRef1.current.setFieldsValue({
    //   'configName': basicInfo.configName
    // })
    //console.log(this.formRef1.current)
    if(JSON.stringify(basicInfo)!=='{}'&&JSON.stringify(databaseConfig)!=='{}'){
      // console.log(databaseConfig);
      return (
        <Fragment>
          <Modal
            title="编辑连接"
            visible={this.state.visible}
            //bodyStyle={{ padding: '12px 24px' }}
            onOk={() => {
              this.formRef1.current
                .validateFields()
                .then(values => {
                  this.handleOk(values,basicInfo,databaseConfig);
                })
                .catch(info => {
                  console.log('Validate Failed:', info);
                });
            }}
            onCancel={this.handleCancel}
          >
            <Form
              name="basic"
              ref={this.formRef1}
              initialValues={{
                configName: basicInfo.configName,
                dataType: databaseConfig.databaseType,
                host: databaseConfig.hostName,
                port: databaseConfig.port,
                userName: databaseConfig.userName,
                password: databaseConfig.password,
                description: basicInfo.description,
                database: databaseConfig.databaseName,
                databaseName: databaseConfig.databaseName,
                master: databaseConfig.hbaseMaster,
                zookeeperQueue: databaseConfig.zookeeperQueue,
                zookeeperPort: databaseConfig.zookeeperPort
              }}
            >
              <Form.Item
                label="数据源名称"
                name="configName"
                rules={[
                  {
                    required: true,
                    message: '请输入数据源名称！',
                  },]}>
                <Input placeholder="请输入数据源名称"/>
              </Form.Item>
              <Form.Item
                label="数据类型"
                name="dataType"
                rules={[
                  {
                    required: true,
                    message: '选择数据类型！',
                  },]}>
                <Select placeholder="选择数据类型" disabled>
                  <Option value="mysql">MySQL</Option>
                  <Option value="sqlserver">SQLServer</Option>
                  <Option value="oracle">Oracle</Option>
                  <Option value="hbase">HBase</Option>
                  <Option value="mongodb">MongoDB</Option>
                </Select>
              </Form.Item>
              { this.dataTypeForm(basicInfo,databaseConfig) }
            </Form>
          </Modal>
        </Fragment>    
      );
    }
    return null;
  }
}

const mapStateToProps = (state) => {
  return {
    databaseConfig: state.getIn(['connection','databaseConfig']).toJS(),
    basicInfo: state.getIn(['connection','basicInfo']).toJS(),
    database: state.getIn(['connection','database']),
  }
}

const mapDispatchToProps = (dispatch) => ({
  getCon(dataType,params){
    dispatch(actionCreators.getConOperation(dataType,params));
  },
  getAllDatabase(dataType,params){
    dispatch(actionCreators.getAllDatabaseOperation(dataType,params));
  },
  cleanDatabase(){
    dispatch(actionCreators.cleanDatabaseOperation());
  },
  testCon(dataType,params){//测试连接
    dispatch(actionCreators.testConOperation(dataType,params));
  },
  editCon(dataType,params,searchValue){
    dispatch(actionCreators.editConOperation(dataType,params,searchValue));
  },
  clearConfig(){
    dispatch(actionCreators.clearConfigOperation());
  }
})

export default connect(mapStateToProps, mapDispatchToProps)(EditConnection);